package com.qjc.demo.algorithm.两个有序链表合并为一个有序链表;

/**
 * @ClassName: MergeSortLinkList
 * @Description: 合并两个有序链表
 * 链表1：    1->2->4
 * 链表2：    1->3->4
 * 结果链表：  1->1->2->3->4->4
 * @Author: qjc
 * @Date: 2022/5/6 2:16 PM
 */
public class MergeSortLinkList {


    public static SortLinkNode mergeSortLink(SortLinkNode l1, SortLinkNode l2) {
        if (l1 == null) return l2;
        if (l2 == null) return l1;
        SortLinkNode resultNode = new SortLinkNode(0);
        SortLinkNode p = resultNode;
        while (l1 != null && l2 != null) {
            if (l1.data <= l2.data) {
                p.next = l1;
                l1 = l1.next;
            } else {
                p.next = l2;
                l2 = l2.next;
            }
            p = p.next;
        }
        if (l1 != null) {
            p.next = l1;
        }
        if (l2 != null) {
            p.next = l2;
        }
        return resultNode.next;
    }

    public static void main(String[] args) {
        SortLinkNode aNode1 = new SortLinkNode(1);
        SortLinkNode aNode2 = new SortLinkNode(2);
        SortLinkNode aNode3 = new SortLinkNode(4);
        aNode1.next = aNode2;
        aNode2.next = aNode3;
        aNode3.next = null;

        SortLinkNode bNode1 = new SortLinkNode(1);
        SortLinkNode bNode2 = new SortLinkNode(3);
        SortLinkNode bNode3 = new SortLinkNode(4);
        bNode1.next = bNode2;
        bNode2.next = bNode3;
        bNode3.next = null;

        SortLinkNode sortLinkNode = mergeSortLink(aNode1, bNode1);
        while (sortLinkNode != null) {
            System.out.println(sortLinkNode.data);
            sortLinkNode = sortLinkNode.next;
        }
    }


}

class SortLinkNode {
    int data;
    SortLinkNode next;

    public SortLinkNode(int data) {
        this.data = data;
    }
}
